﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Repositories;
using System.Data.Linq;
using MvcEngine.Core.Helpers;
using MvcEngine.Core;
using System.Data;

namespace MvcEngine.LinqToSqlProvider.Repositories
{
    public class UnitOfWork : DisposableResource, IUnitOfWork
    {
        private ContextManager contextManager;
        private bool isDisposed;
        private bool isCommitted;
        private bool isRolledBack;

        public UnitOfWork()
        {
            contextManager = new ContextManager(false);
        }

        public void Commit()
        {
            if (isDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            contextManager.Commit();
            isCommitted = true;
            this.contextManager.Dispose();
        }

        protected override void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (!isCommitted && !isRolledBack)
                {
                    this.contextManager.Rollback();
                    this.contextManager.Dispose();
                    isRolledBack = true;
                }
                isDisposed = true;
            }
            base.Dispose(disposing);
        }

        public void Rollback()
        {
            if (!isCommitted && !isRolledBack)
            {
                this.contextManager.Rollback();
                isRolledBack = true;
                this.contextManager.Dispose();
            }
        }
    }
}
